//
//  ChatManager.m
//  DaJiang
//
//  Created by sally on 16/10/1.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "ChatManager.h"

@interface EMChatImageOptions : NSObject <IChatImageOptions>

@property (assign, nonatomic) CGFloat compressionQuality;

@end

@implementation ChatManager

// 参照图片size，按基准尺寸等比压缩
+ (CGSize)compressSizeWithImageSize:(CGSize)imageSize {
  CGFloat markWidth = GNewsDetailPicWidth;
  CGFloat markHeight = GNewsDetailPicHeight;
  //基准尺寸
  CGFloat baseScale = markWidth / markHeight;
  //图片尺寸
  float imageScale = imageSize.width / imageSize.height;

  //按照图片尺寸，等比获取压缩后的尺寸
  if (imageScale > baseScale) {
    markHeight = markWidth / imageScale;
  } else {
    markWidth = markHeight * imageScale;
  }
  return CGSizeMake(markWidth, markHeight);
}

#pragma mark 设置APNS全局属性
+ (void)setNotificationOption {
  EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
  options.displayStyle = ePushNotificationDisplayStyle_messageSummary;
  [[EaseMob sharedInstance].chatManager asyncUpdatePushOptions:options];
}

#pragma mark 设置本地通知，推送环信消息
+ (void)registerLocalNotification:(EMMessage *)message {
  UILocalNotification *notification = [[UILocalNotification alloc] init];
  // 立即触发通知
  NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
  notification.fireDate = fireDate;
  // 时区
  notification.timeZone = [NSTimeZone defaultTimeZone];
  // 设置不重复
  notification.repeatInterval = 0;

  NSString *nickname = [message.ext valueForKey:@"nickname"];
  EMTextMessageBody *body = message.messageBodies[0];
  EMChatText *chat = (EMChatText *) body.chatObject;
  NSString *content = [NSString stringWithFormat:@"%@:%@", nickname, chat.text];

  // 通知内容
  notification.alertBody = content;
  //  notification.alertAction = @"打开应用";
  // 通知被触发时播放的声音 使用默认的
  notification.soundName = UILocalNotificationDefaultSoundName;
  // 通知参数
  NSDictionary *userDict = [NSDictionary dictionaryWithObject:message.conversationChatter forKey:EaseMobChatterKey];
  notification.userInfo = userDict;

  // ios8后，需要添加这个注册，才能得到授权
  if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                             categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  }

  // 执行通知注册
  [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

#pragma mark 移除本地通知，在不需要此通知时记得移除
+ (void)removeNotification {
  [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

// 统计未读消息数
+ (void)setupUnreadMessageCount:(UINavigationController *)nav {
  NSInteger unreadCount = [[EaseMob sharedInstance].chatManager loadTotalUnreadMessagesCountFromDatabase];

  if (nav) {
    if (unreadCount > 0) {
      nav.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i", (int) unreadCount];
    } else {
      nav.tabBarItem.badgeValue = nil;
    }
  }

  UIApplication *application = [UIApplication sharedApplication];
  [application setApplicationIconBadgeNumber:unreadCount];
}

// 添加聊天扩展数据到数据库（用于存储使用 昵称和头像）
+ (void)addExtDateToDB:(Ext *)ext {
  [ChatExtDB creatTable];
  ChatExtDB *newExtDb = [[ChatExtDB alloc] initWithMode:ext];

  //头像、昵称是否改变
  ChatExtDB *extDb = [ChatExtDB queryExtByUserName:ext.username];
  if (extDb && (![ext.avatar isEqualToString:extDb.avatar] || ![ext.nickname isEqualToString:extDb.nickname])) {
    //修改数据库
    [newExtDb modify];
  } else {
    //插入数据库
    [newExtDb insert];
  }
}

+ (EMMessage *)sendTextMessage:(NSString *)text
                            to:(NSString *)toUser
                   messageType:(EMMessageType)messageType
             requireEncryption:(BOOL)requireEncryption
                    messageExt:(NSDictionary *)messageExt {
  // 表情映射。
  //  NSString *willSendText = [EaseConvertToCommonEmoticonsHelper convertToCommonEmoticons:text];
  EMChatText *textChat = [[EMChatText alloc] initWithText:text];
  EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:textChat];
  EMMessage *message = [[EMMessage alloc] initWithReceiver:toUser bodies:[NSArray arrayWithObject:body]];
  message.requireEncryption = requireEncryption;
  message.messageType = messageType;
  message.ext = messageExt;
  EMMessage *retMessage = [[EaseMob sharedInstance].chatManager asyncSendMessage:message
                                                                        progress:nil];

  return retMessage;
}

+ (EMMessage *)sendImageMessageWithImage:(UIImage *)image
                                      to:(NSString *)to
                             messageType:(EMMessageType)messageType
                       requireEncryption:(BOOL)requireEncryption
                              messageExt:(NSDictionary *)messageExt
                                progress:(id<IEMChatProgressDelegate>)progress {
  return [self sendImageMessageWithImage:image to:to messageType:messageType requireEncryption:requireEncryption messageExt:messageExt quality:0.6 progress:progress];
}

+ (EMMessage *)sendImageMessageWithImage:(UIImage *)image
                                      to:(NSString *)to
                             messageType:(EMMessageType)messageType
                       requireEncryption:(BOOL)requireEncryption
                              messageExt:(NSDictionary *)messageExt
                                 quality:(float)quality
                                progress:(id<IEMChatProgressDelegate>)progress {
  id<IChatImageOptions> options = [[EMChatImageOptions alloc] init];
  [options setCompressionQuality:quality];

  EMChatImage *chatImage = [[EMChatImage alloc] initWithUIImage:image displayName:@"image.jpg"];
  [chatImage setImageOptions:options];
  EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithImage:chatImage thumbnailImage:nil];
  EMMessage *message = [[EMMessage alloc] initWithReceiver:to bodies:[NSArray arrayWithObject:body]];
  message.requireEncryption = requireEncryption;
  message.messageType = messageType;
  message.ext = messageExt;
  EMMessage *retMessage = [[EaseMob sharedInstance].chatManager asyncSendMessage:message
                                                                        progress:progress];

  return retMessage;
}

@end
